import configparser
import sys

from PyQt5.QtCore import QTimer
from PyQt5.QtGui import QCursor
from PyQt5.QtNetwork import QUdpSocket, QHostAddress
from PyQt5.QtWidgets import (
    QWidget,
    QApplication,
    QLineEdit,
    QTextEdit,
    QCheckBox,
    QPushButton,
    QComboBox,
    QVBoxLayout,
    QHBoxLayout,
    QLabel, QToolTip,
)


def read_ini_file(file_path):
    config = configparser.ConfigParser()
    config.read(file_path, encoding="utf-8")

    # 将配置转换为字典格式
    config_dict = {}
    for section in config.sections():
        config_dict[section] = {}
        for option in config.options(section):
            config_dict[section][option] = config.get(section, option)

    return config_dict


class HoverComboBox(QComboBox):
    def __init__(self, parent=None):
        super().__init__(parent)

    def enterEvent(self, event):
        self.setStyleSheet("background-color:#e6e6e6;")  # 设置鼠标进入时的样式
        QToolTip.showText(QCursor.pos(), self.currentText())
        super().enterEvent(event)

    def leaveEvent(self, event):
        self.setStyleSheet("background-color:#ff73b3;")  # 设置鼠标离开时的样式
        QToolTip.hideText()
        super().leaveEvent(event)


class QualityFactorTestingTool(QWidget):
    def __init__(self):
        super().__init__()

        self.addressEdit = QLineEdit()
        self.portEdit = QLineEdit()
        self.sendText = QTextEdit()
        self.recvText = QTextEdit()
        self.timerCheckBox = QCheckBox()
        self.sendButton = QPushButton()
        self.sendButton.clicked.connect(self.send_data)
        self.send_time = QLineEdit()
        self.send_time.setVisible(False)
        self.send_data = HoverComboBox()
        self.send_data.setStyleSheet(
            "QComboBox{background-color:rgb(255,255,255);border:1px solid gray;border-radius:3px;padding:1px 18px 1px 3px;min-width:6em;background-color:#ff73b3;}"
        )
        for i in read_ini_file("./config.ini").keys():
            self.send_data.addItem(i)


        self.stop_button = QPushButton()

        layout = QVBoxLayout()

        # layout2 = QHBoxLayout()
        # layout2.addWidget(QLabel("发送地址"))
        # layout2.addWidget(self.addressEdit)
        # layout2.addWidget(QLabel("发送端口"))
        # layout2.addWidget(self.portEdit)

        layout.addWidget(self.addressEdit)
        layout.addWidget(self.portEdit)
        layout.addWidget(self.sendText)
        layout.addWidget(self.recvText)
        layout.addWidget(self.timerCheckBox)
        layout.addWidget(self.send_time)
        layout.addWidget(self.sendButton)
        layout.addWidget(self.send_data)
        layout.addWidget(self.stop_button)

        self.setLayout(layout)

        # 创建UDP套接字
        self.socket = QUdpSocket()
        self.socket.readyRead.connect(self.receive_data)

        # 创建定时器
        self.timer = QTimer(self)
        # self.timer.timeout.connect(self.sendData)

    def timed_transmission(self):
        if self.timerCheckBox == 2:
            self.send_time.setVisible(True)
        else:
            self.send_time.setVisible(False)

    def send_data(self):
        # 获取发送地址和端口
        address = self.addressEdit.text()
        port = int(self.portEdit.text())

        # 获取发送数据
        data = self.sendText.toPlainText().encode()

        # 发送数据
        self.socket.writeDatagram(data, QHostAddress(address), port)

    def receive_data(self):
        # 接收数据
        while self.socket.hasPendingDatagrams():
            data, host, port = self.socket.readDatagram(
                self.socket.pendingDatagramSize()
            )
            self.recvText.setText(data.decode())

    def timer_state_changed(self, state):
        # 启用或禁用定时器
        if state == 2:
            interval = int(self.intervalEdit.text())
            self.timer.start(interval)
        else:
            self.timer.stop()

    def closeEvent(self, event):
        # 关闭定时器和套接字
        self.timer.stop()
        self.socket.close()


if __name__ == "__main__":
    # print(read_ini_file("./config.ini"))
    app = QApplication(sys.argv)
    window = QualityFactorTestingTool()
    window.show()
    sys.exit(app.exec_())
